<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>体检预约系统 - 用户个人信息</title>
    <script src="{{url_for('static', filename='js/jquery-3.6.0.min.js')}}"></script>
    <script src="{{url_for('static', filename='js/custom_message_box.js')}}"></script>
    <link rel="stylesheet" href="{{url_for('static', filename='css/custom_message_box.css')}}">
    <link href="{{url_for('static', filename='css/layui.css')}}" rel="stylesheet">
    <style>
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            margin: 20px;
            padding: 0;
            background: url("{{url_for('static', filename='img/login_admin_web.jpg')}}") no-repeat center;
            background-size: cover;
            height: 800px;
        }

        h1,
        h2 {
            border-bottom: 2px solid #ccc;
            padding-bottom: 5px;
        }

        #profile-info,
        #appointments-list {
            margin-bottom: 20px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-top: 10px;
        }

        th,
        td {
            border: 1px solid #ccc;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .appointment-item {
            margin-bottom: 10px;
            padding: 10px;
            border: 1px solid #ddd;
            background-color: #f9f9f9;
        }

        .logout-btn {
            background-color: #f44336;
            color: white;
            border: none;
            padding: 10px 20px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin-top: 10px;
            cursor: pointer;
        }

        .logout-btn:hover {
            background-color: #d32f2f;
        }

        .cancel-btn {
            background-color: #FF9800;
            color: white;
            border: none;
            padding: 5px 10px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 14px;
            cursor: pointer;
        }

        .cancel-btn.disabled {
            background-color: #ccc;
            /* 禁用时的背景色 */
            cursor: not-allowed;
            /* 鼠标样式为不可点击 */
        }

        .cancel-btn:hover:not(.disabled) {
            background-color: #F57C00;
        }

        #appointments-list {
            background-color: skyblue;
        }

        #profile-info {
            background-color: skyblue;
        }
    </style>
    <script>
        // 获取用户个人信息
        function getPatientProfile() {
            $.ajax({
                url: "{{ url_for('patient.get_patient_profile') }}",
                type: 'GET',
                success: function (response) {
                    if (response.code === 0) {
                        var profile = response.data;
                        $('#profile-id').text(profile.id);
                        $('#profile-username').val(profile.username);
                        $('#profile-name').val(profile.name);
                        $('#profile-id-card-number').val(profile.id_card_number);
                    } else {
                        showMessage("error", response.message, "message", 3000)
                    }
                },
                error: function (xhr, status, error) {
                    showMessage("error", 'Error fetching profile: ' + error, "message", 3000)
                }
            });
        }
        function modifyPatient() {
            event.preventDefault()
            $.ajax({
                url: "{{ url_for('patient.modify_patient_info') }}",
                type: 'POST',
                contentType: "application/json",
                data: JSON.stringify({
                    username: $('#profile-username').val(),
                    name: $('#profile-name').val(),
                    id_card_number: $('#profile-id-card-number').val()
                }),
                success: function (response) {
                    if (response.code === 0) {
                        showMessage("success", "修改成功", "message", 3000)
                    }
                    else {
                        showMessage("error", response.message, "message", 3000)
                    }
                }
            })
        }

        // 异步函数，返回 Promise 对象以处理异步调用
        function getPackageInfoByID(package_id) {
            return new Promise(function (resolve, reject) {
                $.ajax({
                    url: "{{ url_for('doctor.query_package') }}",
                    type: "POST",
                    contentType: "application/json",
                    data: JSON.stringify({ id: package_id }),
                    success: function (response) {
                        if (response.code === 0) {
                            resolve(response.data[0]); // 成功时返回数据
                        } else {
                            reject(response.message); // 失败时返回错误信息
                        }
                    },
                    error: function (xhr, status, error) {
                        reject('Error fetching package info: ' + error); // AJAX 请求失败时返回错误
                    }
                });
            });
        }

        async function getAppointmentsData() {
            try {
                const response = await $.ajax({
                    url: "{{ url_for('patient.get_patient_appointments') }}",
                    type: 'GET'
                });

                if (response.code === 0) {
                    return response.data;
                } else {
                    throw new Error(response.message);
                }
            } catch (error) {
                throw new Error('Error fetching appointments: ' + error);
            }
        }
        function translateToChinese(stringa) {
            switch (stringa) {
                case 'pending':
                    return '待处理';
                case 'accepted':
                    return '已接受';
                case 'rejected':
                    return '已拒绝';
                case 'completed':
                    return '已完成';
                case 'cancelled':
                    return '已取消';
                default:
                    return stringa;
            }
        }
        async function renderAppointments(appointments, selector) {
            var html = '<table>';
            html += '<tr><th>预约编号</th><th>预约套餐名称</th><th>预约套餐描述</th><th>预约时间</th><th>预约状态</th><th>预约结果</th><th>操作</th></tr>';

            for (var i = 0; i < appointments.length; i++) {
                try {
                    // 等待每个 package 信息的获取完成
                    const pkginfo = await getPackageInfoByID(appointments[i].package_id);

                    // 构建表格行
                    html += '<tr>';
                    html += '<td>' + appointments[i].id + '</td>';
                    html += '<td>' + pkginfo.name + '</td>';
                    html += '<td>' + pkginfo.description + '</td>';
                    html += '<td>' + appointments[i].appointment_time + '</td>';
                    html += '<td>' + translateToChinese(appointments[i].status) + '</td>';
                    html += '<td>' + translateToChinese(appointments[i].result) + '</td>';

                    // 根据预约状态确定按钮状态
                    switch (appointments[i].status) {
                        case 'pending':
                            html += '<td><button class="cancel-btn" onclick="cancelAppointment(' + appointments[i].id + ')">取消预约</button></td>';
                            break;
                        case 'cancelled':
                            html += '<td><button class="cancel-btn disabled">已取消</button></td>';
                            break;
                        case 'rejected':
                            html += '<td><button class="cancel-btn disabled">已拒绝</button></td>';
                            break;
                        case 'accepted':
                            html += '<td><button class="cancel-btn disabled">已接受</button></td>';
                            break;
                        case 'completed':
                            html += '<td><button class="cancel-btn disabled">已完成</button></td>';
                            break;
                        default:
                            html += '<td><button class="cancel-btn disabled">未知状态</button></td>';
                            break;
                    }

                    html += '</tr>';
                } catch (error) {
                    console.error('Error fetching package info:', error);
                    // 处理 package 信息获取失败的情况
                }
            }

            html += '</table>';

            // 更新 HTML 到指定的元素
            $(selector).html(html);
        }
        async function refreshPatientAppointments() {
            try {
                const appointments = await getAppointmentsData();
                await renderAppointments(appointments, '#appointments-list');
            } catch (error) {
                alert(error);
            }
        }


        // 取消预约函数
        function cancelAppointment(appointmentId) {
            $.ajax({
                url: "{{ url_for('patient.cancel_appointment') }}",
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ id: appointmentId }),
                success: function (response) {
                    if (response.code === 0) {
                        showMessage("success", '预约已成功取消', "message", 3000)
                        // 刷新预约列表
                        refreshPatientAppointments();
                    } else {
                        showMessage("error", response.message, "message", 3000);
                    }
                },
                error: function (xhr, status, error) {
                    showMessage("error", 'Error cancelling appointment: ' + error, "message", 3000);
                }
            });
        }

        $(document).ready(function () {
            // 假设session中的patient_id已经通过某种方式存储，这里用localStorage模拟
            var patient_id = localStorage.getItem('patient_id');

            // 调用函数以获取数据
            getPatientProfile();
            refreshPatientAppointments();

            // 添加退出登录功能
            $('#logoutBtn').click(function () {
                // 清除本地存储或者其他操作以注销用户
                localStorage.removeItem('patient_id');
                // 可以重定向到登录页面或其他逻辑
                window.location.replace("{{ url_for('patient.login_patient_web') }}");
            });

        });
    </script>
</head>

<body>
    <div id="message"></div>
    <h1>用户个人信息</h1>
    <div id="profile-info">
        <form action="" method="post">
            <p>ID: <span id="profile-id"></span></p>
            <label for="profile-username">用户名</label>
            <input type="text" id="profile-username" class="profile-username"></input>
            <label for="profile-name">姓名</label>
            <input type="text" id="profile-name" class="profile-name"></input>
            <label for="profile-id-card-number">身份证</label>
            <input type="text" id="profile-id-card-number" class="profile-id-card-number"></input>
            <button type="submit" onclick="modifyPatient()">修改信息</button>
        </form>
    </div>

    <h2>用户预约信息</h2>
    <button class="layui-btn layui-btn-normal"><a
            href="{{ url_for('patient.appointment_patient_web') }}">前往预约</a></button>
    <div id="appointments-list"></div>

    <!-- 退出登录按钮 -->
    <button style="text-align: center" class="layui-btn layui-btn-normal layui-btn-radius">
        <a href="{{ url_for('patient.dashboard_patient_web') }}">返回面板主页</a>
    </button>

    <!-- 其他页面内容 -->
</body>

</html>